import { Button, Modal, message } from "antd";
import SelectOneOrderModal from "./SelectOneOrderModal";
import { useState } from "react";
import { useScanRegistrationStore } from "../../store";
import { fieldMap } from "../../fieldMap";

const DeleteGoods = props => {
	const { currentSelectGoods, orderList, updateState } = useScanRegistrationStore();
	const [modal] = Modal.useModal();

	async function handleDeleteGoodsClick() {
		const selectData = Object.keys(currentSelectGoods);
		
		if (!selectData.length) {
			message.warning("请勾选数据");
			return;
		}

		// 是否是原售后单商品，如果是原售后单商品不可删除
		let isOriginalGoods = false
		const deleteGoodsIdMap = {}
		selectData.forEach(key => {
			currentSelectGoods[key].forEach((item) => {
				if (!item[fieldMap['是否是新增商品']]) {
					isOriginalGoods = true
				}

				if (!deleteGoodsIdMap[key]) {
					deleteGoodsIdMap[key] = []
				}
				deleteGoodsIdMap[key].push(item[fieldMap['售后商品id']])
			});
		});
		
		if (isOriginalGoods) {
			message.warning("原售后单信息不可删除");
			return
		}

		await modal.confirm({
			title: "提示",
			content: "是否确认删除选择的商品"
		});

		// 执行删除逻辑
		Object.keys(deleteGoodsIdMap).forEach(key => {
			const afterSalesIndex = orderList.findIndex(item => item[fieldMap['售后单号']] === key)
			const goodsList = orderList[afterSalesIndex][fieldMap['售后商品列表']]
			deleteGoodsIdMap[key].forEach(id => {
				const index = goodsList.findIndex(item => item[fieldMap['售后商品id']] === id)
				goodsList.splice(index, 1)
			})
			orderList[afterSalesIndex][fieldMap['售后商品列表']] = goodsList
		})
		
		updateState({
			orderList: JSON.parse(JSON.stringify(orderList))
		})
		message.success("删除成功");
	}

	return (
		<>
			<Button onClick={handleDeleteGoodsClick}>删除商品</Button>
		</>
	);
};

export default DeleteGoods;
